/*
 * Copyright (c) 2017 22420103@QQ.COM 版权所有
 */
package com.lehe.service.impl;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.lehe.common.Contants;
import com.lehe.common.crypt.Md5Encrypt;
import com.lehe.common.exceptions.LHAdminException;
import com.lehe.common.exceptions.LHException;
import com.lehe.common.utils.StringUtil;
import com.lehe.dao.AgentInfoDao;
import com.lehe.dao.UserChargeGoldCoinLogDao;
import com.lehe.dao.UserInfoDao;
import com.lehe.dao.UserManagerDao;
import com.lehe.entry.AdminUserMappingDto;
import com.lehe.entry.AgentInfoDto;
import com.lehe.entry.UserChargeGoldCoinLogDto;
import com.lehe.entry.UserInfoDto;
import com.lehe.entry.UserPayDetailDto;

/**
 * 用户代理操作
 *
 * @author 王丹
 * @since 2017-02-26
 */
@Transactional
@Service
public class UserManagerService extends AbstractService {

    @Autowired
    private AgentInfoDao agentInfoDao;
    @Autowired
    private UserInfoService userInfoService;
    @Autowired
	private UserManagerDao userManagerDao;
    
    @Autowired
	private UserInfoDao userInfoDao;
    
    @Autowired
    private AdminUserMappingService adminUserMappingService;
    @Autowired
    private UserChargeGoldCoinLogDao userChargeGoldCoinLogDao;

    /**
     * 设置代理
     * @param userId 要设置成代理的玩家id
     * @param agentId 要设置成代理的玩家上级代理id或agentid
     * @param adminUserId 将新设置成代理的玩家关联到后台用户的后台用户id
     * @param roleId 如果权限为1的话，就是管理员角色，不需要插入用户关联数据
     * @return
     * @throws LHException 
     */
    public void createAgent(Long userId, Long agentId,Integer userLvel,Long adminUserId, Long roleId) throws LHAdminException{
        
        //查询出要设置代理的玩家信息
        UserInfoDto playerInfo = userInfoService.queryUserInfo(userId, null);
        
        if(playerInfo == null){
        	throw new LHAdminException("玩家id【"+userId+"】信息不存在");
        }
        
        if(!playerInfo.getAgentId().equals(0L)){
        	throw new LHAdminException("玩家id【"+userId+"】已经是代理，不能再设置为代理");
        }
        
        //查询出要设置代理玩家的上级代理信息,agentId参数接收的值可能为userid，也可能为agentid，因此先根据userid查询
        UserInfoDto fatherInfo = null;
        if(!agentId.equals(0L)){
        	fatherInfo = userInfoService.queryUserInfo(agentId, null);
            //没查询到再根据agentid查询
            if(fatherInfo == null){
            	fatherInfo = userInfoService.queryUserInfoByAgentId(agentId);
            }
            
            if(fatherInfo == null){
            	throw new LHAdminException("上级代理id【"+agentId+"】信息不存在");
            }
            if(null == fatherInfo.getAgentId() || fatherInfo.getAgentId().intValue() <= 0){
                throw new LHAdminException("上级代理id【"+agentId+"】不是代理用户");
            }
            if(!StringUtil.isCreateAgent(fatherInfo.getUserLevel())){
            	throw new LHAdminException("上级代理id【"+agentId+"】代理级别不够");
            }
        }else{
        	throw new LHAdminException("上级代理id不能为0");
        }
        
        //更新玩家用户表
        UserInfoDto updateDto = new UserInfoDto();
        updateDto.setUserId(playerInfo.getUserId());
        updateDto.setAgentId(playerInfo.getUserId());
        updateDto.setFatherAgentId(fatherInfo == null?0L:fatherInfo.getAgentId());
        updateDto.setUserLevel(userLvel);
        userInfoService.updateAccountByUserId(updateDto);

        //插入AgentInfo信息
        AgentInfoDto agentSubInfoDto = new AgentInfoDto();
        agentSubInfoDto.setUserId(updateDto.getUserId());
        agentSubInfoDto.setAgentId(updateDto.getAgentId());
        agentSubInfoDto.setfAgentId(fatherInfo == null?0L:fatherInfo.getAgentId());
        agentSubInfoDto.setAgentPassword(Md5Encrypt.md5(" "));//??密码哪里来
        agentSubInfoDto.setPhoneNum("");//??哪里来
        agentSubInfoDto.setLoginRight(updateDto.getUserLevel());
        insertAgentInfo(agentSubInfoDto);
        
        //插入后台用户与玩家用户关联表数据
        if(1 != roleId){
            AdminUserMappingDto d = new AdminUserMappingDto();
            d.setAdminUserId(adminUserId);
            d.setUserId(userId);
            adminUserMappingService.insertAdminUserMapping(d);
        }

    }

    public void chargeJB(Long userId, Long count, Long roleId) throws LHAdminException{
        if(count>99999){
            throw new LHAdminException("充值金币数大于99999");
        }
        if(1 != roleId){
            throw new LHAdminException("只有管理员才有此权限");
        }
        UserInfoDto dest = userInfoService.queryUserInfo(userId,null);
        if(dest == null){
            throw new LHAdminException("要充值的目标玩家不存在");
        }
        userManagerDao.chargeJB(userId,count);
        UserChargeGoldCoinLogDto userChargeGoldCoinLogDto = new UserChargeGoldCoinLogDto();
        userChargeGoldCoinLogDto.setJuniorUserId(userId);
        userChargeGoldCoinLogDto.setSuperiorUserId(Contants.ADMIN_AGENT_ID);
        userChargeGoldCoinLogDto.setSuperiorAgentId(Contants.ADMIN_AGENT_ID);
        userChargeGoldCoinLogDto.setChargeCount(count);
        userChargeGoldCoinLogDto.setSourceType(Contants.USER_CHARGE_SOURCE_TYPE_ADMIN);
        userChargeGoldCoinLogDto.setCreateTime(LocalDateTime.now());
        userChargeGoldCoinLogDao.insert(userChargeGoldCoinLogDto);
    }

    /**
     * 插入代理表数据
     * @param agentInfoDto
     * @return
     */
    public int insertAgentInfo(AgentInfoDto agentInfoDto){
        return agentInfoDao.insertAgentInfo(agentInfoDto);
    }
    
    public Map<String,Object> queryIndexData(List<Long> ids,List<Long> agentIds){
		
		//在线人数
		Integer onlineCount = userManagerDao.queryOnlineCount();
		//下属玩家
		Integer subPlayerCount = userManagerDao.queryUserPlayerCount(null,null,null, ids);
		//下属代理
		Integer subAgentCount = ids.size();
		if(subAgentCount == 0){
			subAgentCount = userManagerDao.queryAllAgentCount();
		}
		//充值总额
		String totalFeeCountStr = userManagerDao.queryTotalFeeCountByAgentIds(ids,agentIds);
		//今日充值总额
		String todayTotalFeeCount = userManagerDao.queryTotalFeeCountByAgentIdsToday(ids,agentIds);
		//今日充值笔数
		Integer todayTotalCount = userManagerDao.queryTotalCountByAgentIdsToday(ids,agentIds);
		
		List<UserPayDetailDto> newest = userManagerDao.queryNewestCharge(ids,agentIds);
		
		Map<String,Object> result = new HashMap<String,Object>();
		result.put("onlineCount", onlineCount);
		result.put("subPlayerCount", subPlayerCount);
		result.put("subAgentCount", subAgentCount);
		result.put("totalFeeCountStr", totalFeeCountStr);
		result.put("todayTotalFeeCount", todayTotalFeeCount);
		result.put("todayTotalCount", todayTotalCount);
		result.put("newest", newest);
		
		return result;
	}

	public void deleteAgent(Long userId) throws LHAdminException {
		List<String> ids = new ArrayList<String>();
		ids.add(userId.toString());
		List<UserInfoDto> tmp = userInfoDao.queryUserInfos(ids);
		
		if(tmp == null || tmp.isEmpty()){
			throw new LHAdminException("要解除代理的用户不存在【"+userId+"】");
		}
		
		UserInfoDto user = tmp.get(0);
		
		if(user.getAgentId() == null || user.getAgentId().intValue() == 0){
			throw new LHAdminException("要解除代理的用户还不是代理");
		}
		
		if(user.getAgentId() == null || user.getAgentId().intValue() == 0){
			throw new LHAdminException("要解除代理的用户还不是代理");
		}
		
		//查询下属代理个数
		Integer count = userManagerDao.queryUserAgentCount(null,user.getAgentId(),null,null,null);
		if(count > 0){
			throw new LHAdminException("要解除代理的用户已经有"+count+"个下属代理，不能解除");
		}
		//查询下属玩家个数
		List<Long> tmpIds = new ArrayList<Long>();
		tmpIds.add(userId);
		count = userManagerDao.queryUserPlayerCount(null,null,null,tmpIds);
		if(count > 0){
			throw new LHAdminException("要解除代理的用户已经有"+count+"个下属玩家，不能解除");
		}
		
		//1更新用户agentid为0，代理等级为0
        UserInfoDto updateDto = new UserInfoDto();
        updateDto.setUserId(user.getUserId());
        updateDto.setAgentId(0L);
        updateDto.setUserLevel(0);
        userInfoService.updateAccountByUserId(updateDto);
        
        //2删除AgentInfo
        agentInfoDao.deleteAgentInfoByUserId(user.getUserId());
        
        //删除后台用户与玩家用户关联表数据
        adminUserMappingService.deleteByUserId(user.getUserId());
      
	}
}
